/**
 * By Qing
 * 2017/1/30
 */
import axios from 'axios';
import qs from 'qs';

const siteConfig = {
	'root': 'http://127.0.0.1:3000',
};
const log = console.log;
const app = {};
/**
 * @des Request
 */
app.request = function(opts) {
	const _this = this,
		config = {
			method: 'GET',
			baseUrl: siteConfig.root,
			withCredentials: true,
			responseType: 'json',
			timeout: 10000,
		};
	app.objExtends(config, opts);
	app.showLoading();
	// axios.interceptors.request.use(config => {
	// 	return config;
	// });
	axios(config).then(res => {
		app.hideLoading();
		typeof opts.success === 'function' && opts.success.call(_this, res);
	}).catch(err => {
		app.hideLoading();
		typeof opts.error === 'function' && opts.error.call(_this, err);
	});
	// axios.interceptors.response.use(res => {
	// 	console.log('38...............', res);
		
	// 	return res;
	// })
};
/**
 * @des showLoading
 */
app.showLoading = function(opts) {
	log('加载中。。。', opts);
};
/**
 * @des hideLoading
 */
app.hideLoading = function() {
	log('加载完成。。。');
};
// Prompt message
app.flash = function(status, msg) {
  let  _parseDom = (arg) => {
    let objEle = document.createElement('div')
    objEle.innerHTML = arg;
    return objEle.childNodes;
  };
  let _clearDom = () => {
    let flash = document.getElementById('flash');
    flash.parentNode.removeChild(flash);
  }
  let bgColor = '';
  status=='success'?bgColor='#c8e5bc':
  (status=='error'?bgColor='#e7c3c3':
  (status=='warning'?bgColor='#f5e79e':bgColor=''));
  let tpl = `<div id="flash">
              <div class="prompt" style="background-color:${bgColor};">
                <span class="ms">${msg}</span>
              </div>
            </div>`;
  let render = _parseDom(tpl);
  document.body.append(render[0]);
  setTimeout(_clearDom, 5000);
}
// Parse DOM
app.parseDom = function(arg) {
  let objEle = document.createElement('div')
  objEle.innerHTML = arg;
  return objEle.childNodes;
}
// Set web-storage
app.setStorage = function(key, value) {
  let curTime = Date.now();
  localStorage.setItem(key, JSON.stringify({data: value, time: curTime}));
}
// Remove web-storage 
app.rmStorage = function(key) {
  localStorage.removeItem(key);
}
// Get web-storage
app.getStorage = function(key) {
	let data = JSON.parse(localStorage.getItem(key));
  return data;
}
// 防抖
app.debounce = function(fn, delay) {
  var timer = null;
  return function() {
    var context = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  };
}
// 简单倒计时
app.exampleTimer = function() {
  var val = 60,
      timer = null;
  function time() {
    if(val === 0) {
      clearInterval(timer);
      return false;
    }else {
      val--;
      return val;
    }
  }
  timer = setInterval(function() {
    time();
  }, 1000)
}
// 脚本过滤
app.filter = function(str) {
  let s = '';
  if(str.length == 0) return '';
  s = str.replace(/&/g, "&gt;");
  s = s.replace(/</g, "&lt;");
  s = s.replace(/>/g, "&gt;");
  s = s.replace(/\s/g, "&nbsp;");
  s = s.replace(/'/g, "&#39;");
  s = s.replace(/"/g, "&quot;");
  s = s.replace(/\n/g, "<br>");
  return s;
}
// 表单验证
app.validity = function(type, string) {
  let str = string.trim();
  let s = str.replace(/&/g,'').replace(/</g,'')
          .replace(/>/g,'').replace(/\s/g,'')
          .replace(/'/g,'').replace(/"/g,'')
          .replace(/\n/g,''),
      len = s.length;
  if(str.length == 0) return false;
  switch(type) {
    case 'name':
      return len > 8 ? false : true;
      break;
    case 'pass':
      return (len < 6 || len > 16) ? false : true;
      break;
    default:
      return false;
  }
}
// 时间格式
app.dateTime = function(tm, cfg) {
	var baseConfig = {
		'mode': 'static', // 'static'/'dynamic'
		'format': 'YY-MM-DD h:m:s d',
		'htm': 'body'
	};
	// tm = Number(tm);
	cfg = (cfg === undefined || cfg === null || ((typeof cfg) != 'object')) ? baseConfig : app.objExtends(baseConfig, cfg);
	// 1.Get original Time
	var t, time = '';
	t = !tm ? new Date() : new Date(tm);
	var YY = t.getFullYear(),
		$m = t.getMonth()+1,
		MM = ad0($m),
		$d = t.getDate(),
		DD = ad0($d),
		d = weekTrans(t.getDay()),
		$h = t.getHours(),
		h = ad0($h),
		$m = t.getMinutes(),
		m = ad0($m),
		$s = t.getSeconds(),
		s = ad0($s);
	if(cfg.mode == 'static') {
		switch(cfg.format) {
			case 'YY-MM-DD': 
				time = YY +'-'+ MM +'-'+ DD;
				break;
			case 'h:m:s':
				time = h+':'+m+':'+s;
				break;
			case 'YY-MM-DD h:m:s':
				time = YY +'-'+ MM +'-'+ DD +' '+h+':'+m+':'+s;
				break;
			default:
				time = YY +'-'+ MM +'-'+ DD +' '+h+':'+m+':'+s+' '+d;
		}
		return time;
	}else if(cfg.mode == 'dynamic') {
		var timer = null, curH = '';
		timer = setInterval(function() {
			$s++;
			if($s >=60) {
				$m++;
				$s = 0;
			}
			if($m >= 60) {
				$h++;
				$m = 0;
			}
			if($h >= 24) {
				$h = 0;
			}
			curH = ad0($h) +':'+ ad0($m) +':'+ ad0($s);
			$v.getdom(cfg.htm)[0].innerText = curH;
		}, 1000);
	}
	// Handle week
	function weekTrans(day) {
		switch(day) {
			case 1:
				return '星期一';
				break;
			case 2:
				return '星期二';
				break;
			case 3:
				return '星期三';
				break;
			case 4:
				return '星期四';
				break;
			case 5:
				return '星期五';
				break;
			case 6:
				return '星期六';
				break;
			default:
				return '星期日';
				break;
		}
	}
	// Additional '0'
	function ad0(val) {
		return val < 10 ? ('0' + val) : val;
	}
	
	return time;
}
// 值存在性判断
app.hasValue = function(val) {
	if(val === '' || val === undefined || val === null) return false;
	if(isNaN(val)) {
		if(typeof val === 'object') {
			if(Array.isArray(val)) {
				if(val.length > 0) return true;
				return false;
			}
			if(Object.keys(val).length > 0) return true;
			return false;
		}
	}else {
		return true;
	}
}
// object extends
app.objExtends = function(base, son) {
	for(var p in son) {
		base[p] = son[p];
	}
	return base;
}
/** 生成随机字符串 */
app.getRandomStr = function(len) {
	var str = '';
	for(; str.length < len; str += Math.random().toString(36).substr(2));
	return str.substr(0, len);
}
/** 正则匹配 */
app.match = (type, str) => {
	let res = null;
	switch(type) {
	  // 匹配邮箱
	  case 'email':
		const EmailReg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
		res = EmailReg.test(str);
		break;
	  // (新)匹配手机号
	  case 'mobile':
		const mobileReg = /^1[0-9]{10}$/;
		res =  mobileReg.test(str);
		break;
	  // 匹配8-16位数字和字母密码的正则表达式
	  case 'pass':
		const passReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
		res = passReg.test(str);
		break;
	  // 匹配国内电话号码 0510-4305211
	  case 'phone':
		const phoneReg = /\d{3}-\d{8}|\d{4}-\d{7}/;
		res = phoneReg.test(str);
		break;
	  // 匹配身份证号码
	  case 'idcard':
		const idcardReg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		res = idcardReg.test(str);
		break;
	  // 匹配腾讯QQ号
	  case 'qq':
		const qqcardReg = /[1-9][0-9]{4,}/;
		res = qqcardReg.test(str);
		break;
	  // 匹配ip地址
	  case 'ip':
		const ipReg = /\d+\.\d+\.\d+\.\d+/;
		res = ipReg.test(str);
		break;
	  // 匹配中文
	  case 'zh':
		const zhReg = /^[\u4e00-\u9fa5]*$/;
		res = zhReg.test(str);
		break;
	}
}
/** 平台检测 */
app.platform = type => {
	let isWechat = /micromessenger/i.test(navigator.userAgent),
		isWeibo = /weibo/i.test(navigator.userAgent),
		isQQ = /qq\//i.test(navigator.userAgent),
		isIOS = /(iphone|ipod|ipad|ios)/i.test(navigator.userAgent),
		isAndroid = /android/i.test(navigator.userAgent);
	
}
/** 排序算法 */
app.sequenceAlgorithm = arr => {
	let res = [...arr];
	let val = res[Math.floor(Math.random()*(res.length - 1))];
	/** Min SEQUENCE */
	// let len = res.length;
	// for(let i = 0; i<len; i++) {
	//     let minV = Math.min(...res.slice(i));
	//     let pos = res.indexOf(minV);
	//     res.splice(pos, 1);
	//     res.unshift(minV);
	// }
  
	/** 冒泡排序 */
	// const swap = (res, ia, ib) => {
	//     [res[ia], res[ib]] = [res[ib], res[ia]];
	// };
	// let len = res.length-1;
	// for(let i = len; i>0; i--) {
	//     for(let j = 0; j<i; j++) {
	//         if(res[j] < res[j+1]) {
	//             swap(res, j, j+1);
	//         }
	//     }
	// }
  
	/** 二分排序 */
	// for (var i = 1; i < res.length; i++) {
	//     var key = res[i], left = 0, right = i - 1;
	//     while (left <= right) {
	//         var middle = parseInt((left + right) / 2);
	//         if (key < res[middle]) {
	//             right = middle - 1;
	//         } else {
	//             left = middle + 1;
	//         }
	//     }
	//     for (var j = i - 1; j >= left; j--) {
	//         res[j + 1] = res[j];
	//     }
	//     res[left] = key;
	// }
  
	/** 希尔排序 */
	// const len = res.length;
	// let gap = Math.floor(len / 2);
  
	// while (gap > 0) {
	//     // gap距离
	//     for (let i = gap; i < len; i++) {
	//         const temp = res[i];
	//         let preIndex = i - gap;
	
	//         while (res[preIndex] > temp) {
	//             res[preIndex + gap] = res[preIndex];
	//             preIndex -= gap;
	//         }
	//         res[preIndex + gap] = temp;
	//     }
	//     gap = Math.floor(gap / 2);
	// }
	/** 二分搜索法 */
	let ret = [];
  
	log(ret);
	return ret;
}
/** 单例 */
app.single = function(fn) {
	var result;
	return result || (result = fn.apply(this, arguments));
}
/** 节流函数/防止频繁提交 */
app.proxySynData = function() {
	var cache = {},
		timer;
	return function(id) {
	  if(!timer) {
		timer = setTimeout(function() {
		  synData(Object.keys(cache).join());
		  cache = {};
		  clearTimeout(timer);
		  timer = null;
		}, 1000)
	  }
	  cache[id] = 1;
	}
}
/** 观察者模式 */
app.Observer = (function() {
	const _messages = {};
	return {
		regist: function(type, fn) {
			if(typeof _message[type] === undefined) {
				_messages[type] = [fn];
			}else {
				_messages[type].push(fn);
			}
		},
		fire: function(type, args) {
			if(!_messages[type]) {
				return;
			}
			let events = {
				type: type,
				args: args || {}
			},
			i = 0,
			len = _messages[type].length;
			for(i; i < len; i++) {
				_messages[type][i].call(this, events);
			}
		},
		remove: function(type, fn) {
			if(_messages[type] instanceof Array) {
				let i = _messages[type].length - 1;
				for(i; i >= 0; i--) {
					_messages[type][i] === fn && _messages[type].splice(i, 1);
				}
			}
		}
	}
})()
/** 模板渲染函数 */
app.formatString = (str, data) => {
	return str.replace(/\{\{(\w+)\}\}/g, function(match, key) {
	  return typeof data[key] === undefined ? '' : data[key]
	})
}
/** 移动端适配 */
app.mobileAdapter = (function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            var fontSize = 20;
            docEl.style.fontSize = fontSize + 'px';
            var docStyles = getComputedStyle(docEl);
            var realFontSize = parseFloat(docStyles.fontSize);
            var scale = realFontSize / fontSize;
            console.log("realFontSize: " + realFontSize + ", scale: " + scale);
            fontSize = clientWidth / 667 * 20;
            if(isIphoneX()) fontSize = 19;
            fontSize = fontSize / scale;
            docEl.style.fontSize = fontSize + 'px';
        };
    // Abort if browser does not support addEventListener
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);

    // iphoneX判断
    function isIphoneX(){
        return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
    }

})/** (document, window) **/

window.addEventListener('readystatechange', () => {
	console.log('页面渲染中*******')
}, false);

export default app;